Python 24-Day Course - Day 2: Working with Strings

Day 2: Working with Strings

f-strings (Formatted Strings)

name = "John"
age = 25
print(f"{name} is {age} years old.")
# John is 25 years old.

String Methods

text = "  Hello, World!  "

text.strip()       # "Hello, World!"
text.lower()       # "  hello, world!  "
text.upper()       # "  HELLO, WORLD!  "
text.replace("World", "Python")  # "  Hello, Python!  "
text.split(",")    # ["  Hello", " World!  "]

String Slicing

s = "Python"
s[0]      # 'P'
s[-1]     # 'n'
s[0:3]    # 'Pyt'
s[::2]    # 'Pto'
s[::-1]   # 'nohtyP' (reversed)

Multi-line Strings

message = """
Hello.
This is a multi-line string.
Indentation is preserved.
"""

Today’s Exercises

  1. Create a self-introduction sentence using an f-string.
  2. Split an email address into the username and domain based on the @ symbol.
  3. Convert the string "python" to "PYTHON".

Was this article helpful?